using System;
using System.Text;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class UiUtils {
  /// <summary>
  /// 为任意UI控件添加点击事件监听
  /// </summary>
  /// <param name="target">目标UI控件</param>
  /// <param name="callback">点击回调</param>
  /// <param name="eventType">事件类型(默认为点击事件)</param>
  public static void AddUIListener(GameObject target,
                                 Action callback,
                                 EventTriggerType eventType = EventTriggerType.PointerClick) {
    // 确保目标对象有效
    if (target == null) {
      Debug.LogError("AddUIListener失败：目标对象为null");
      return;
    }

    // 获取或添加EventTrigger组件
    var trigger = target.GetComponent<EventTrigger>();
    if (trigger == null) {
      trigger = target.AddComponent<EventTrigger>();
    }

    // 创建事件项
    var entry = new EventTrigger.Entry {
      eventID = eventType
    };

    // 添加回调监听
    entry.callback.AddListener((data) => { callback.Invoke(); });

    // 确保triggers列表已初始化
    if (trigger.triggers == null) {
      trigger.triggers = new System.Collections.Generic.List<EventTrigger.Entry>();
    }

    // 添加事件项
    trigger.triggers.Add(entry);

  }

  /// <summary>
  /// 根据最大字符数自动换行
  /// </summary>
  /// <param name="input">输入文本</param>
  /// <param name="max_char">每行最大字符数</param>
  /// <returns>处理后的带换行文本</returns>
  public static string AutoWrapText(string input, int max_char) {
    if (string.IsNullOrEmpty(input) || max_char <= 0) {
      return input;
    }

    StringBuilder result = new StringBuilder(input.Length + (input.Length / max_char + 1));
    int currentLineLength = 0;

    for (int i = 0; i < input.Length; i++) {
      char c = input[i];

      // 遇到已有换行符则重置计数器
      if (c == '\n') {
        currentLineLength = 0;
        result.Append(c);
        continue;
      }

      // 达到最大字符数时插入换行
      if (currentLineLength >= max_char) {
        // 检查是否需要处理单词完整性（英文等）
        if (char.IsWhiteSpace(c) || i == 0 || char.IsWhiteSpace(input[i - 1])) {
          // 在空格处直接换行
          result.Append('\n');
          currentLineLength = 0;
        } else {
          // 在字符中间插入软换行
          result.Append('\n');
          currentLineLength = 0;
        }
      }

      result.Append(c);
      currentLineLength++;
    }

    return result.ToString();
  }

  /// <summary>
  /// 计算当前分辨率相对于目标分辨率的缩放比例
  /// </summary>
  /// <param name="referenceWidth">参考分辨率宽度</param>
  /// <param name="referenceHeight">参考分辨率高度</param>
  /// <param name="mode">适配模式(0=按宽度,1=按高度,2=按完整区域)</param>
  /// <returns>缩放比例</returns>
  public static float GetResolutionScale(int referenceWidth, int referenceHeight, int mode = 0) {
    // 获取当前屏幕/游戏视图分辨率
    int currentWidth = Screen.width;
    int currentHeight = Screen.height;

    // 计算宽高比例
    float widthRatio = (float)currentWidth / referenceWidth;
    float heightRatio = (float)currentHeight / referenceHeight;

    // 根据模式返回不同的缩放比例
    switch (mode) {
      case 0: // 按宽度缩放
        return widthRatio;

      case 1: // 按高度缩放
        return heightRatio;

      case 2: // 按完整区域缩放(取较小比例)
        return Mathf.Min(widthRatio, heightRatio);

      default:
        return 1f; // 默认不缩放
    }
  }

  /// <summary>
  /// 获取当前分辨率与目标分辨率的宽高比差异
  /// </summary>
  /// <param name="referenceWidth">参考宽度</param>
  /// <param name="referenceHeight">参考高度</param>
  /// <returns>(宽度比例, 高度比例)</returns>
  public static Vector2 GetResolutionRatios(int referenceWidth, int referenceHeight) {
    return new Vector2(
        (float)Screen.width / referenceWidth,
        (float)Screen.height / referenceHeight
    );
  }
}
